package com.example.springboot006web.controller;

import com.example.springboot006web.repository.User;
import com.example.springboot006web.repository.UserInfo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description: TODO
 * @author: uu
 * @data: 2023/6/24 17:19
 * @version: v1.0
 */
@org.springframework.stereotype.Controller
public class Controller {

    @GetMapping("/get001")
    @ResponseBody
    public User test01(){
        return new User("cms","234");
    }


    @GetMapping("/get002")
    public String test02(@RequestParam(name = "n",required = true) String name, @RequestParam(name = "a",required = false,defaultValue = "18") Integer age){
        return "name="+name+",age="+age;
    }

    @PostMapping("/get003")
    @ResponseBody
    public User test03(@RequestBody User user){
        return user;
    }

    // 使用reader 和inputStream读取post请求体的数据
    @PostMapping("/get004")
    @ResponseBody                           // 这里一定要有这个注解
    public String test04(Reader reader){
        StringBuffer content = new StringBuffer("");
        try(BufferedReader bin = new BufferedReader(reader)){
            var line = "";
            while ((line = bin.readLine()) != null){
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return content.toString();
    }

    @GetMapping("/get005")
    @ResponseBody
    public String get005(Integer id[]){
        List<Integer> integers = Arrays.stream(id).toList();
        return integers.toString();
    }

    @GetMapping("/get006")
    @ResponseBody
    public UserInfo get006(@Validated UserInfo userInfo, BindingResult bindingResult){
        return userInfo;
    }

    @PostMapping("/get007")
    @ResponseBody
    public Map<String, Object> addUserInfo(@Validated(UserInfo.EditGroup.class) @RequestBody UserInfo userInfo, BindingResult bin){
        Map<String, Object> map = new HashMap<>();
        if (bin.hasErrors()){
            for (int i = 1 ,len =  bin.getErrorCount(); i <= len ; i++){
                FieldError fieldError = bin.getFieldErrors().get(i - 1);
                map.put(i+"-"+fieldError.getField(),fieldError.getDefaultMessage());
            }
        }
        System.out.println(userInfo);
        return map;
    }
}
